<template>
  <Button
    class="action-button action btn-inline"
    :shape="btnShape"
    :class="{'action-loading':loading}"
    :loading="loading"
    v-if="actionShow"
    :icon="btnIcon || actionModel.icon"
    :type="btnType"
    @click="actionTrigger"
  >
    {{actionText || actionModel.name}}
    </Button>
</template>
<script>
import $ from '@/common';
export default {
	props: {
		model: {},
		index: {},
		row: {},
	},
	data() {
		return {
			loading: false,
			btnIcon: null,
			actionText: null,
			status: 1,
		};
	},
	computed: {
		param() {
			return this.actionModel.param || {};
		},
		btnShape() {
			return this.param.button_stype === 'circle' ? 'circle' : null;
		},
		btnType() {
			if (this.param.button_type) {
				return this.param.button_type;
			}
			if (this.actionModel._button_type) {
				return this.actionModel._button_type;
			} else {
				return 'ghost';
			}
		},
		actionShow() {
			if (this.actionModel.type === 'webcall') {
				return false;
			}
			if (this.actionModel.locate === 'inline' && (!this.actionModel.dev || $.dev)) {
				if (this.actionModel.param && this.actionModel.param.condition) {
					let data = this.row;
					data;
					try {
						return eval(eval('`' + this.actionModel.param.condition + '`'));
					} catch (ex) {
						console.warn(ex);
						return false;
					}
				} else {
					return true;
				}
			} else {
				return false;
			}
		},
	},
	created() {
		this.actionModel = this.model;
	},
	mounted() {
		this.$owner = this.$parent.$owner || $.getParent(this, 'actionOwner', true);
		if (!this.$owner) {
			this.$owner = this.$parent;
		}
		//在action读取完成事件中设置主action关系
		this.$owner.$once('action-loaded:' + this.actionModel.code, () => {
			this.findMainModel();
		});
	},
	methods: {
		findMainModel() {
			this.$mainAction = this.$owner.$actionCollection.getAction(this.actionModel.code);
			if (this.$mainAction && this.$mainAction.$inlineMirror) {
				this.$mainAction.$inlineMirror[this.index] = this;
			}
			return this.$mainAction;
		},
		actionTrigger() {
			if (!this.$mainAction) {
				this.findMainModel();
			}
			if (this.actionModel.param && this.actionModel.param.loading) {
				this.loading = true;
			}
			var trigger = this.$parent.actionTrigger({
				code: this.actionModel.code,
				row: this.row,
				index: this.index,
				data: this.row.id,
			});
			if (trigger && trigger.finally) {
				this.loading = true;
				trigger
					.catch(ex => {
						console.error(ex);
					})
					.finally(() => {
						this.loading = false;
					});
			}
			return trigger;
		},
	},
};
</script>
<style lang="less">
.btn-inline {
	margin: 2px 0;
}

.btn-inline + .btn-inline {
	margin-left: 4px;
	margin-right: 0;
}
</style>

